package cn.liontalk.controller;

import cn.liontalk.VO.ResultVO;
import cn.liontalk.converter.OrderFormToOrderDTOConvter;
import cn.liontalk.dto.OrderDTO;
import cn.liontalk.enums.ResultEnums;
import cn.liontalk.exception.OrderException;
import cn.liontalk.form.OrderForm;
import cn.liontalk.service.OrderService;
import cn.liontalk.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhouZhe
 * @version 1.0
 * @description
 * @date 2019-04-16 22:16
 **/
@RestController
@RequestMapping(value = "/order")
@Slf4j
public class OrderController {

    @Autowired
    OrderService orderService;

    @PostMapping("/create")
    public ResultVO createOrder(@Valid OrderForm orderForm, BindingResult result){

        if(result.hasErrors()){
            log.error("【创建订单】 参数不正确,orderForm  ={}",orderForm);
            throw  new OrderException(ResultEnums.PARAM_ERROR.getCode(),result.getFieldError().getDefaultMessage());
        }

        OrderDTO orderDTO = OrderFormToOrderDTOConvter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车信息为空");
            throw new OrderException(ResultEnums.CART_EMPTY);
        }

        OrderDTO resultDTO = orderService.create(orderDTO);

        Map<String, String> map = new HashMap<>();
        map.put("orderId", resultDTO.getOrderId());
        return ResultVOUtil.success(map);
    }

}
